
import 'package:barcode_scan2/barcode_scan2.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '/utils/dialog.dart';

class ScanToText extends StatefulWidget {
  const ScanToText({super.key});

  @override
  State<StatefulWidget> createState() => _ScanToTextState();
}

class _ScanToTextState extends State<ScanToText> {
  String _content = "";

  Future<void> onPressScan(BuildContext context) async {
    // 异步扫码
    var options = const ScanOptions(
        android: AndroidOptions(aspectTolerance: 0.5, useAutoFocus: true),
        autoEnableFlash: false,
        strings: {'cancel': '退出', 'flash_on': '开启闪光灯', 'flash_off': '关闭闪光灯'});
    var result = await BarcodeScanner.scan(options: options);
    // 提取结果
    if (result.type == ResultType.Barcode) {
      if (result.format == BarcodeFormat.qr) {
      } else if (result.format == BarcodeFormat.unknown) {
        return showAlertDialogSafely(context, "二维码格式错误：${result.formatNote}");
      } else {
        return showAlertDialogSafely(context, "二维码格式错误：${result.format.name}");
      }
    } else if (result.type == ResultType.Error) {
      return showAlertDialogSafely(context, "扫码失败： ${result.rawContent}");
    } else {
      return;
    }
    // 处理文本
    setState(() {
      _content = result.rawContent;
    });
  }

  Future<void> onPressCopy() {
    return Clipboard.setData(ClipboardData(text: _content));
  }

  void onPressClear() {
    setState(() {
      _content = "";
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: <Widget>[
        Expanded(
          child: Container(
              margin: const EdgeInsets.all(30.0),
              padding: const EdgeInsets.all(20.0),
              alignment: Alignment.topLeft,
              decoration: ShapeDecoration(
                  shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(20),
                side: BorderSide(
                  width: 2,
                  color: Theme.of(context).colorScheme.primary,
                  style: BorderStyle.solid,
                ),
              )),
              child: _buildContentText(context)),
        ),
        Container(
            margin: const EdgeInsets.only(left: 10, right: 10, bottom: 20),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                TextButton.icon(
                  icon: const Icon(Icons.copy),
                  label: const Text("复制"),
                  onPressed: onPressCopy,
                ),
                TextButton.icon(
                  icon: const Icon(Icons.qr_code_scanner),
                  label: const Text("扫一扫"),
                  onPressed: () => onPressScan(context),
                ),
                TextButton.icon(
                  icon: const Icon(Icons.clear),
                  label: const Text("清空"),
                  onPressed: onPressClear,
                )
              ],
            )),
      ],
    );
  }

  Widget _buildContentText(BuildContext context) {
    return _content.isNotEmpty
        ? SelectableText(_content)
        : Text(
            "扫一扫查看二维码内容",
            style: TextStyle(
                color: Theme.of(context).colorScheme.secondaryContainer),
          );
  }
}
